﻿using System;
using System.Net;
using Tisonet.Dobrak.Client.WP8.Helpers;
using Tisonet.Dobrak.Domain.Models;

namespace Tisonet.Dobrak.Client.WP8.Services.Movies
{
    public class WebMoviesProvider : IRemoteMoviesProvider
    {
        private readonly Uri _serverUri;

        public WebMoviesProvider(Uri serverUri )
        {
            _serverUri = serverUri;
        }

        public void DownloadMovieAsync(string movieId, Action<Movie> onReady)
        {
            if (movieId == null) throw new ArgumentNullException("movieId");
            
            var webClient = new WebClient();

            webClient.OpenReadCompleted += (sender, args) => DataDownloaded(args, onReady);
            Uri requestUri = CreateRequestUri(movieId);

            webClient.OpenReadAsync(requestUri);
        }

        private Uri CreateRequestUri(string id)
        {
            return new Uri(string.Format("{0}/{1}", _serverUri, id));
        }
       
        private void DataDownloaded(OpenReadCompletedEventArgs e, Action<Movie> onDownloaded)
        {
            if (e.Cancelled || e.Error != null)
            {
                return;
            }

            var movie = JsonSerializerHelper.Deserialize<Movie>(e.Result);

            if (onDownloaded != null)
            {
                onDownloaded(movie);
            }
        }
    }
}
